package com.joysuch.wwyt.datadump.biz.condition;

import cn.zlg.common.datadump.condition.CustomQueryConditionBuilder;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.entity.dsl.QBpDepart;
import com.joysuch.wwyt.bp.entity.investigate.BpInvestigateStore;
import com.joysuch.wwyt.bp.entity.investigate.dsl.QBpInvestigateStoreDetail;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpInvestigateStoreRepository;
import com.joysuch.wwyt.bp.service.impl.BpDepartServiceImpl;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.SimpleExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class BpInvestigateStoreFindSubstoreConditionBuilder implements CustomQueryConditionBuilder {

    @Autowired
    private BpInvestigateStoreRepository storeRepository;

    @Override
    public Predicate build(String name, SimpleExpression propertyPath, Object value) {
        Long storeId = (Long) value;
        if(storeId == 0L) {
            return null;
        }
        BpInvestigateStore bpInvestigateStore = storeRepository.findById(storeId).orElseThrow(() -> new RuntimeException("操作失败"));
        List<Long> storeIdList = Lists.newArrayList();
        if (!bpInvestigateStore.getTopOrNot()) {
            List<BpInvestigateStore> storeList = storeRepository.findByParentId(storeId);
            for (BpInvestigateStore store : storeList) {
                if (!store.getTopOrNot()) {
                    List<BpInvestigateStore> stores = storeRepository.findByParentId(store.getId());
                    for (BpInvestigateStore investigateStore : stores) {
                        storeIdList.add(investigateStore.getId());
                    }
                } else {
                    storeIdList.add(store.getId());
                }
            }
        } else {
            storeIdList.add(storeId);
        }
        QBpInvestigateStoreDetail q = QBpInvestigateStoreDetail.bpInvestigateStoreDetail;
        // 为空时，给一个不可能实现的条件，达到返回空集的效果
        return storeIdList.isEmpty() ? q.storeId.eq(-1L) : q.storeId.in(storeIdList);
    }


}
